package simtools.xml.test;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.Set;

import org.jdom.*;
import org.jdom.input.SAXBuilder;

/**
 * Basic JDOM Example Outputs Top News Stories from Moreover.com Example usage:
 * java news1
 */

public class News1 {

	// Download and Process XML File
	public void process(String url) {
		try {
			// Use SAXBuilder
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new File(url));
			extractNewsStories(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Walk through JDOM Tree and extract all articles
	// For each article, print article ID, headline text and source
	private void extractNewsStories(Document doc) {
		Element root = doc.getRootElement();
		total(root);
		/*
		// Get all children named, "article"
		List articles = root.getChildren("article");
		Iterator i = articles.iterator();
		System.out.println("Number of Articles:  " + articles.size());
		while (i.hasNext()) {
			Element article = (Element) i.next();
			String articleID = article.getAttributeValue("id");
			Element headline = article.getChild("headline_text");
			String headlineText = headline.getText();
			// Alternative, compact text is commented below
			// headlineText = article.getChild("headline_text").getText();
			String source = article.getChild("source").getText();
			String harvestTime = article.getChild("harvest_time").getText();
			System.out.print(articleID + ":  " + headlineText + " (" + source
					+ ":  ");
			System.out.println(harvestTime + ")");
		}
		*/
	}
	
	@SuppressWarnings("unchecked")
	private int total(Element root) {
		List<Element> articles = root.getChildren("Link");
		Set<String> a = new HashSet<String>();
		Iterator<Element> i = articles.iterator();
		
		while (i.hasNext()) {
			Element article = i.next();
			String nodeTo = article.getChild("NodeTo").getText();
			String nodeFrom = article.getChild("NodeFrom").getText();
			
			a.add(nodeTo);
			a.add(nodeFrom);
		}
		
		System.out.println(a.size());
		return a.size();
	}

	public static void main(String[] args) {
		System.out.println("Today's Top News Stories");
		News1 news = new News1();
		news.process("C:/Kalil/workspace/TxtToXml/src/Routers.xml");
	}

}